package org.example.service.imp;

import org.example.dao.CommentDao;
import org.example.domain.Comment;
import org.example.domain.User;
import org.example.service.CommentService;
import org.example.util.UserThreadLocalUtil;
import org.example.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CommentServiceImp implements CommentService {
    @Autowired
    private CommentDao commentDao;
    @Autowired
    private LikeServiceImp likeServiceImp;
    @Override
    public int saveOne(Comment comment) {
        if (comment==null) return 0;

        return commentDao.saveOne(comment);
    }

    /**
     *
     * @param entityId  具体帖子的评论
     * @param entityType  0 -一级评论 2-评论的评论 -1不按照这个条件查询
     * @param targetId 0 -帖子的评论  其他都是父评论的id
     * @param start mysql 分页的offset
     * @param page mysql 分页的size
     * @return
     */
    @Override
    public List<Comment> searchByFilterCondition(int entityId, int entityType,int targetId,int start,int page) {
        return commentDao.searchByFilterCondition(entityType,entityId,targetId,start,page);
    }
    @Autowired
    private UserThreadLocalUtil userThreadLocalUtil;
    @Autowired
    private UserServiceImp userServiceImp;
    public CommentVO change(Comment comment){
        if (comment == null) return null;
        CommentVO result = new CommentVO();
        result.setComment(comment);
        User user = userServiceImp.searchById(comment.getUserId());
        result.setCommentUser(user);
        //点赞的数量   和   当前用户是否已赞
        Integer likeCount = likeServiceImp.getLikeCount(2, comment.getId());
        result.setLike(likeCount);
        boolean like = likeServiceImp.currUserIsLike(2, comment.getId(), userThreadLocalUtil.get().getId());
        result.setCurrIsLike(like);
        return result;
    }
    public List<CommentVO> changes(List<Comment> commentList){
        if (commentList == null ) return null;
        List<CommentVO> result = new ArrayList<>();
        if (commentList.size() == 0) return result;

        for (int i = 0;i<commentList.size();i++){
            result.add(change(commentList.get(i)));
        }
        return result;
    }

    @Override
    public int searchCount(int entityType, int entityId, int targetId) {
        return commentDao.searchCount(entityType,entityId,targetId);
    }

    @Override
    public User searchReplyUser(int commentId) {
        return commentDao.searchReplyUser(commentId);
    }

    @Override
    public List<Integer> searchUserPublishCommentIds(int userId) {
        if (userId<=0) return null;
        return commentDao.searchUserPublishCommentIds(userId);
    }

    @Override
    public Comment searchById(int commentId) {
        if (commentId<=0) return null;
        return commentDao.searchById(commentId);
    }
}
